﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.Common;

namespace TidyBlog.Data
{
    /// <summary>
    /// 分页辅助类
    /// </summary>
    public abstract class PagingHelper<T> where T : new()
    {
        /// <summary>
        /// 执行请求的命令对象
        /// </summary>
        public readonly IDbCommand Cmd = DbHelper.CreateCommand();
        /// <summary>
        /// SELECT命令生成器
        /// </summary>
        public readonly SelectCommand SQLCommand = new SelectCommand(SimpleORM<T>.TableName);


        public PagingHelper()
        {
            SQLCommand.Select(SimpleORM<T>.ListColumns).OrderBy(SimpleORM<T>.SortColumns);
        }

        /// <summary>
        /// 获取记录总数
        /// </summary>
        /// <returns>记录总数</returns>
        protected virtual int GetRowCount()
        {
            var tempSelectColumns = SQLCommand.SelectColumns;
            var tempSortColumns = SQLCommand.SortColumns;

            Cmd.CommandText = SQLCommand.Select("COUNT(*)").Top(0).OrderBy(new SortColumn[0]).ToString();
            var result = Convert.ToInt32(DbHelper.ExecuteScalar(Cmd));

            SQLCommand.Select(tempSelectColumns).OrderBy(tempSortColumns);

            return result;
        }

        /// <summary>
        /// 获取数据
        /// </summary>
        /// <param name="pageSize">每页显示记录数</param>
        /// <param name="currentPage">当前页</param>
        /// <returns>数据</returns>
        protected abstract List<T> GetData(ushort pageSize, int currentPage);

        /// <summary>
        /// 执行查询
        /// </summary>
        /// <param name="pageSize">每页显示记录数</param>
        /// <param name="currentPage">当前页</param>
        /// <returns>查询结果</returns>
        public DataPaging<T> Execute(ushort pageSize, int currentPage)
        {
            DataPaging<T> dataPaging = new DataPaging<T>(this.GetRowCount(), pageSize, currentPage);
            if (dataPaging.RowCount > 0)
            {
                dataPaging.Data = this.GetData(pageSize, dataPaging.CurrentPage);
            }

            return dataPaging;
        }
    }
}